package wechat

import (
	"context"
	"log"
	"nearby/biz/common"
	redis "nearby/biz/dal/cache"

	"github.com/silenceper/wechat/v2/miniprogram/encryptor"
)

func GetWxSession(ctx context.Context, wxCode string) (session *WxSession, err error) {
	defer func() {
		log.Printf("wxCode: %v; session: %v, err: %+v", wxCode, session, err)
	}()

	key := redis.WxCodePrefix + wxCode
	if val := redis.Get(ctx, key).Val(); val != "" {
		log.Printf("redis.Get, key is %+v, val is %+v", key, val)
		return ToSession(val), nil
	}
	// 如果没从缓存里取出来
	session, err = getWxSession(ctx, wxCode)
	if err != nil {
		log.Printf("GetWxSession fail, getWxSession err: %+v", err)
		return nil, err
	}
	// 将得到的session装入redis缓存
	_ = redis.Set(ctx, key, session.ToString(), common.Day)
	return session, nil
}

func getWxSession(ctx context.Context, wxCode string) (*WxSession, error) {
	miniAuth := mini.GetAuth()
	res, err := miniAuth.Code2Session(wxCode)
	if err != nil {
		log.Printf("getWxSession fail, miniAuth.Code2Session fail, err: %+v", err)
		return nil, err
	}
	log.Printf("miniAuth.Code2Session, res: %+v, err: %+v", res, err)
	return ToSession(res), nil
}

func DecryptData(ctx context.Context, sessionKey string, encryptData string, iv string) (plainData *encryptor.PlainData, err error) {
	miniEncryptor := mini.GetEncryptor()
	plainData, err = miniEncryptor.Decrypt(sessionKey, encryptData, iv)
	if err != nil {
		return nil, err
	}
	return plainData, nil
}
